package com.easybuilder.blog.service.impl;

import com.easybuilder.blog.dao.BlogFansDao;
import com.easybuilder.blog.dto.BlogFansDTO;
import com.easybuilder.blog.entity.BlogFans;
import com.easybuilder.blog.service.FansService;
import com.easybuilder.common.base.entity.Page;
import com.easybuilder.common.utils.UserUtil;
import com.easybuilder.core.rbac.entity.SysUser;
import com.easybuilder.core.rbac.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FansServiceImpl implements FansService {

    @Resource
    private BlogFansDao blogFansDao;
    @Autowired
    private SysUserService sysUserService;

    /** 关注 */
    @Override
    public int attention(Long userId) {
        int result = 0;
        // 获取当前用户
        SysUser user = UserUtil.getUser();
        if (user != null) {
            // 先检查是否存在关注记录
            Example example = new Example(BlogFans.class);
            example.createCriteria().andEqualTo("fansId", user.getId()).andEqualTo("attentionId", userId);
            List<BlogFans> blogFans = blogFansDao.selectByExample(example);
            if (blogFans != null && blogFans.size() > 0) {
                // 重新关注
                result = repeatAttention(blogFans);
            } else {
                // 新的关注
                result = newAttention(user, userId);
            }
            return result;
        }
        return 0;
    }

    /** 重新关注 */
    private int repeatAttention(List<BlogFans> blogFans) {
        BlogFans fans = blogFans.get(0);
        if (fans.getDropStatus().equals(0)) {
            return 1;
        }
        fans.setDropStatus(0);
        fans.setUpdateTime(new Date());
        return blogFansDao.updateByPrimaryKeySelective(fans);
    }

    /** 新的关注 */
    private int newAttention(SysUser user, Long userId) {
        BlogFans fans = new BlogFans();
        fans.setFansId(user.getId());
        fans.setFansNickname(user.getNickname());
        fans.setFansImg(user.getImg());
        fans.setFansSign(user.getSign());
        fans.setDropStatus(0);
        fans.setCreateTime(new Date());
        // 获取被关注用户
        SysUser sysUser = sysUserService.getUserById(userId);
        if (sysUser != null) {
            fans.setAttentionId(sysUser.getId());
            fans.setAttentionNickname(sysUser.getNickname());
            fans.setAttentionImg(sysUser.getImg());
            fans.setAttentionSign(sysUser.getSign());
        }
        return blogFansDao.insertSelective(fans);
    }

    /** 取消关注 */
    @Override
    public int cancelAttention(Long userId) {
        SysUser user = UserUtil.getUser();
        if (user != null) {
            // 当前用户id
            Long fansId = user.getId();
            // 先查询当前用户关注该用户的记录
            BlogFans blogFans = blogFansDao.selectByFansIdAndAttentionId(fansId, userId);
            // 如果该关注记录已逻辑删除，则代表当前用户已经取消关注指定人，返回取消成功
            if (blogFans != null && blogFans.getDropStatus().equals(1)) {
                return 1;
            }
            int update = blogFansDao.cancleAnnotation(fansId, userId);
            return update;
        }
        return 0;
    }

    /** 粉丝列表分页查询
     * @return*/
    @Override
    public Page<BlogFansDTO> fansPage(int pageNum, int pageSize) {
        Page<BlogFansDTO> page = new Page<BlogFansDTO>();
        SysUser user = UserUtil.getUser();
        if (user != null) {
            Long userId = user.getId();
            // 获取粉丝总量
            Long total = blogFansDao.countFans(userId);
            // 获取粉丝分页数据
            List<BlogFans> list = blogFansDao.fansPage(pageNum * pageSize, pageSize, userId);
            // 设置其他参数
            List<BlogFansDTO> result = setOtherParams(list);
            // 组织返回值
            page.setTotal(total).setList(result);
        }
        return page;
    }

    /** 关注列表分页查询 */
    @Override
    public Page<BlogFans> attentionPage(int pageNum, int pageSize) {
        Page<BlogFans> page = new Page<BlogFans>();
        SysUser user = UserUtil.getUser();
        if (user != null) {
            Long userId = user.getId();
            // 获取粉丝总量
            Long total = blogFansDao.countAttention(userId);
            // 获取粉丝分页数据
            List<BlogFans> list = blogFansDao.annotationPage(pageNum * pageSize, pageSize, userId);
            // 组织返回值
            page.setTotal(total).setList(list);
        }
        return page;
    }

    @Override
    public List<BlogFans> selectByExample(Example example) {

        return blogFansDao.selectByExample(example);
    }

    @Override
    public Long countFans(Long userId) {
        if (userId == null) {
            return null;
        }
        return blogFansDao.countFans(userId);
    }

    @Override
    public Long countAttention(Long userId) {
        if (userId == null) {
            return null;
        }
        return blogFansDao.countAttention(userId);
    }


    /** 设置其他参数 */
    private List<BlogFansDTO> setOtherParams(List<BlogFans> list) {
        List<BlogFansDTO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (BlogFans blogFans : list) {
                BlogFansDTO fansDTO = new BlogFansDTO();
                BeanUtils.copyProperties(blogFans, fansDTO);
                result.add(fansDTO);
            }
        }
        // 设置互相关注标识
        setBothAttention(result);
        return result;
    }

    private void setBothAttention(List<BlogFansDTO> list) {
        // 获取粉丝id集合
        List<Long> fansIds = list.stream().map(fans -> { return fans.getFansId();}).collect(Collectors.toList());
        if (fansIds == null || fansIds.size() == 0) {
            return;
        }
        // 获取当前登陆人id
        SysUser user = UserUtil.getUser();
        if (user != null) {
            // 查找粉丝集合是否在当前登陆人的关注范围内
            Example example = new Example(BlogFans.class);
            example.createCriteria().andEqualTo("fansId", user.getId()).andIn("attentionId", fansIds).andEqualTo("dropStatus", 0);
            List<BlogFans> blogFans = blogFansDao.selectByExample(example);
            if (!CollectionUtils.isEmpty(blogFans)) {
                List<Long> attentionIds = blogFans.stream().map(fans -> { return fans.getAttentionId();}).collect(Collectors.toList());
                // 遍历粉丝集合，设置互相关注标识
                for (BlogFansDTO fans : list) {
                    // 如果当前粉丝id，包含在登陆人关注列表，设置为互相关注
                    if (attentionIds.contains(fans.getFansId())) {
                        fans.setBothAttention(true);
                    }
                }
            }
        }
    }
}
